package com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl;

import com.iwhalecloud.bss.kite.common.constant.TableConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.cucc.order.accept.chain.AbstractOrderHandler;
import com.iwhalecloud.bss.kite.cucc.order.accept.constructor.DataConstructorManager;
import com.iwhalecloud.bss.kite.cucc.order.util.AcceptUtils;
import com.iwhalecloud.bss.kite.dataservice.entity.OrderItem;
import com.iwhalecloud.bss.kite.dataservice.entity.inst.OfferObjInstRel;
import com.iwhalecloud.bss.kite.dataservice.entity.order.OrderItemChange;
import com.iwhalecloud.bss.kite.dataservice.mapper.inst.OfferObjInstRelMapper;
import com.iwhalecloud.bss.kite.dataservice.mapper.order.OrderItemChangeMapper;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.order.client.dto.OrderContainer;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import com.iwhalecloud.bss.kite.order.client.dto.WithdrawOrderRequest;
import com.ztesoft.bss.base.staticdata.CoreDataInteract;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wjy
 */
@Component
public class DerivedOrderHandle extends AbstractOrderHandler {
    @Override
    public void doHandle(OrderRequest request) {
        if (request instanceof WithdrawOrderRequest) {
            WithdrawOrderRequest orderRequest = (WithdrawOrderRequest) request;
            List<OrderItem> deleteOrderItems = orderRequest.getDeleteOrderItems();
            // 计算所有变动的offer-inst的明细进行生成撤单修正衍生单。
            List<String> orderItemIds = deleteOrderItems.stream().map(OrderItem::getOrderItemId).distinct().collect(Collectors.toList());
            OrderItemChangeMapper orderItemChangeMapper = SpringUtil.getBean(OrderItemChangeMapper.class);
            Example em = new Example(OrderItemChange.class);
            em.createCriteria().andIn("orderItemId", orderItemIds).andEqualTo("tableName", "OFFER_INST");
            //获取当前撤单订单项原单变动
            List<OrderItemChange> orderItemChanges = orderItemChangeMapper.selectByExample(em);
            //获取整个订单
            String oldCustOrderId = orderRequest.getOldCustOrderId();
            Example example = new Example(OrderItemChange.class);
            example.createCriteria().andEqualTo("custOrderId", oldCustOrderId).andNotIn("orderItemId", orderItemIds);
            List<OrderItemChange> orderItemChangesbyCustOrderId = orderItemChangeMapper.selectByExample(example);
            //对比撤单的订单项中实例中offer_inst的所有明细与客户订单的offer_obj_inst_rel对比，然后进行筛选
            List<OrderItemChange> othObjRelChanges = orderItemChangesbyCustOrderId.stream().filter(t -> KiteStringUtils.equals(t.getTableName(),"OFFER_OBJ_INST_REL")).collect(Collectors.toList());
            //筛选出需要的明细，进行生成订单项处理， 然后反操作变动信息
            List<OrderItemChange> changesItem = new ArrayList<>();

            List<OrderItemChange> otherOrderItemChanges = collectOtherOrder(othObjRelChanges, orderItemChanges);
            if (KiteListUtils.isNotEmpty(otherOrderItemChanges)) {
                OrderItem newIterm = createOrderItemDerived(orderRequest);
                otherOrderItemChanges.forEach(change -> {
                    // 更新变动的客户订单，时间，主键
                    change.setCustOrderId(newIterm.getCustOrderId());
                    change.setOrderItemId(newIterm.getOrderItemId());
                    change.setHandleTime(new Date());
                    change.setChgId(SeqUtils.getNext(TableConsts.OrderItemChange));

                    // TODO 修改实例actiontype为M
                    if (ActionType.A.name().equals(change.getActionType())) {
                        change.setActionType(ActionType.M.name());
                    }
                    change.setInstStateChg(AcceptUtils.withDrawInstStateChg(change.getInstStateChg()));

                    String newValue = change.getFieldValue();
                    String oldValue = change.getOldFieldValue();
                    change.setFieldValue(oldValue);
                    change.setOldFieldValue(newValue);
                    change.setActionType(ActionType.M.name());
                    changesItem.add(change);
                });
                request.getOrderContainer().getOrderItemChangeMap().put(newIterm.getOrderItemId(), changesItem);
            }
            // 撤单实例值还原处理
            DataConstructorManager.buildInstData(request, changesItem);
        }
    }

    private OrderItem createOrderItemDerived(WithdrawOrderRequest request) {
        OrderItem newOrderItem = new OrderItem();

        String orderItemId = SeqUtils.genOrderItemId(request.getLanId());
        newOrderItem.setOrderItemId(orderItemId);
        newOrderItem.setAskId(orderItemId);
        newOrderItem.setCustOrderId(request.getCustOrderId());
        newOrderItem.setAcceptMode(request.getAcceptMode());
        newOrderItem.setOrderSource(request.getAskSource());
        // 订单项类型：销售品类
        newOrderItem.setOrderItemCd(CoreDataInteract.EVT_0003_1200);
        // 订单项状态：受理中
        newOrderItem.setStatusCd(CoreDataInteract.EVT_0001_100000);
        newOrderItem.setStatusDate(LocalDateTime.now());

        newOrderItem.setUndoFlag("F");

//        orderItem.setApplyObjSpec(compInst.getOfferId());
//        orderItem.setObjId(compInst.getOfferInstId());
//        orderItem.setOfferKind(compInst.getOfferType());
        newOrderItem.setApplyObjSpec("-1");
        newOrderItem.setObjId("-1");
        newOrderItem.setOfferKind("-1");
        newOrderItem.setAccNbr("-1");
        newOrderItem.setBelongLanId(request.getLanId());
        newOrderItem.setRegionId(request.getRegionId());

        newOrderItem.setAcceptRegionId(request.getRegionId());
        newOrderItem.setAcceptStaffId(request.getStaffId());
        newOrderItem.setAcceptLanId(request.getLanId());
        newOrderItem.setCreateOrgId(request.getOrgId());
        newOrderItem.setAcceptDate(request.getAcceptDate());
        newOrderItem.setCreateDate(request.getAcceptDate());
        newOrderItem.setCreateStaff(request.getStaffId());
        newOrderItem.setCreatePost(request.getPostId());
        newOrderItem.setUpdatePost(request.getPostId());
        newOrderItem.setUpdateOrg(request.getOrgId());
        newOrderItem.setOrderHandlerId(request.getStaffId());
        newOrderItem.setCustWorksheetId(orderItemId);
        newOrderItem.setPreHandleFlag("0");
        newOrderItem.setServiceOfferId(request.getServiceOfferId());
        newOrderItem.setIsCharge("00F");
        newOrderItem.setVerNum("0");
        newOrderItem.setParOrderItemId("-1");
        newOrderItem.setPriority("0");
        newOrderItem.setSkipOpen("F");
        newOrderItem.setBelongCustId(request.getCustId());
        newOrderItem.setNewBelongCustId(request.getCurrentCustId());
        //处理order_item.remark字段,从公共属性获取
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        String remark = querySceneInstService.getCommonAttrValue(request.getMainSceneInstId(), "remark");
        newOrderItem.setRemark(remark);

        //变更类型 旧订单置空
        newOrderItem.setOperType(CoreDataInteract.EVT_C_0003_1100);
        newOrderItem.setOldOrderItemId("-1");
        //取原单的服务
        newOrderItem.setServiceOfferId(request.getServiceOfferId());
        OrderContainer.ofRequest(request).addOrderItem(newOrderItem);
        return newOrderItem;
    }

    private  List<OrderItemChange>  collectOtherOrder(List<OrderItemChange> othObjRelChanges, List<OrderItemChange>  orderItemChanges) {
        List<OrderItemChange> newChange = new ArrayList<>();
        othObjRelChanges.stream().forEach(t -> {
            String instId = t.getInstId();
            OfferObjInstRelMapper offerObjInstRelMapper = SpringUtil.getBean(OfferObjInstRelMapper.class);
            OfferObjInstRel offerObjInstRel = offerObjInstRelMapper.selectByPrimaryKey(instId);
            String offerInstId = offerObjInstRel.getOfferInstId();
            OrderItemChange itemChange = orderItemChanges.stream().findFirst().filter(f -> t.getInstId().equals(offerInstId)).orElse(null);
            if (null != itemChange) {
                OrderItemChange change = t;
                change.setInstStateChg(itemChange.getInstStateChg());
                change.setActionType(itemChange.getActionType());
                newChange.add(change);
            }

        });

        return newChange;
    }
}
